import { useState, useEffect, useContext } from "react";
import {
  Box,
  Text,
  Flex,
  IconButton,
  Collapse,
  useToast,
  Modal,
  ModalOverlay,
  ModalHeader,
  ModalContent,
  ModalCloseButton,
  ModalBody,
  ModalFooter,
  Button,
  useDisclosure,
  RadioGroup,
  Stack,
  Radio,
} from "@chakra-ui/react";
import { ChevronDownIcon, ChevronUpIcon } from "@chakra-ui/icons";
import newKeyInfos from "@/src/config/newKeyInfos.json"; // 确保路径正确
import { KeyGroup } from "@/src/types/types.v1";
import { MainContext } from "@/src/providers/MainProvider";
import { useTranslation } from "@/src/i18n";
import { getAppList } from "@/src/config/appConfig";

const SystemKey = () => {
  const {
    connectedMouse,
    mouseKeys,
    setMouseKeys,
    selKeyIndex,
    profile,
    profileIndex,
  } = useContext(MainContext);
  const toast = useToast();
  const [nowIndex, setNowIndex] = useState<string | null>(null);
  // 为 keyData 定义一个类型
  const [keyData, setKeyData] = useState<KeyGroup[]>([]);
  const { t } = useTranslation("");
  const { isOpen, onOpen, onClose } = useDisclosure();
  const [currentApp, setCurrentApp] = useState<string | null>("1");
  const [openAppInfo, setOpenAppInfo] = useState<any>(null);
  const [appList, setAppList] = useState(getAppList());

  // 加载新键位信息
  useEffect(() => {
    if (newKeyInfos?.systemKey?.list) {
      const updatedKeyData = newKeyInfos.systemKey.list.map((item) => ({
        ...item,
        show: true, // 初始设置所有项目为折叠状态
      }));
      setKeyData(updatedKeyData);
    }
  }, []);

  // 更新鼠标按键配置的通用方法
  const updateMouseKeyConfig = (
    keyInfo: any,
    index: number,
    sIndex: number
  ) => {
    const newKey = {
      ...mouseKeys[selKeyIndex],
      keyName: t(keyInfo.name),
      type: keyInfo.type,
      code1: keyInfo.code1,
      code2: keyInfo.code2,
      code3: keyInfo.code3,
    };

    const updatedMouseKeys = mouseKeys.map((key) =>
      key.index === selKeyIndex ? newKey : key
    );

    setMouseKeys(updatedMouseKeys);
    profile.updateMouseKeys(profileIndex, updatedMouseKeys);
    if (connectedMouse) {
      connectedMouse.setMouseKeys(updatedMouseKeys, profileIndex);
    }
    setNowIndex(`${index}-${sIndex}`);
    toast({
      title: `${t("haveSet")}：${t(keyInfo.name)}`,
      status: "info",
      duration: 3000,
      isClosable: true,
      colorScheme: "blue",
      position: "top",
    });
  };

  // 处理按键点击
  const handleClick = (index: number, sIndex: number) => {
    if (selKeyIndex == 0) {
      toast({
        title: t("leftBtnNoChange"),
        status: "info",
        duration: 3000,
        isClosable: true,
        colorScheme: "blue",
        position: "top",
      });
      return;
    }
    const keyInfo = newKeyInfos.systemKey.list[index].keycodes[sIndex];

    if (keyInfo.name === "openApp") {
      const data = {
        keyInfo,
        index,
        sIndex,
      };
      setOpenAppInfo(data);
      onOpen();
      return;
    }

    updateMouseKeyConfig(keyInfo, index, sIndex);
  };

  // 切换显示/隐藏状态
  const toggleItem = (index: number) => {
    setKeyData((prevData) =>
      prevData.map((item, i) =>
        i === index ? { ...item, show: !item.show } : item
      )
    );
  };

  const handleAppChange = (value: string) => {
    console.log("value", value);
    setCurrentApp(value);
    setAppList(
      appList.map((app) => ({
        ...app,
        checked: app.value.toString() === value,
      }))
    );
  };

  const submitOpenApp = () => {
    const { keyInfo, index, sIndex } = openAppInfo;
    const newKeyInfo = { ...keyInfo, code1: Number(currentApp) };
    console.log("newKeyInfo", newKeyInfo);

    updateMouseKeyConfig(newKeyInfo, index, sIndex);
    onClose();
  };

  return (
    <>
      <Box className="h-full">
        <Text className="mb-4 text-sm font-semibold text-[#eeeeee]">
          {t("systemAssignTip")}
        </Text>
        <Box
          className="flex flex-col space-y-6 overflow-y-auto pr-2"
          sx={{
            height: "calc(100vh - 420px)", // 减去头部和其他固定元素的高度
            minHeight: "300px", // 设置最小高度
          }}
        >
          {keyData.map((item, index) => (
            <Box key={index} className="w-full">
              <Flex
                className="items-center justify-between h-[36px] rounded-lg shadow-sm cursor-pointer"
                onClick={() => toggleItem(index)}
              >
                <Text className="text-lg font-semibold text-white">
                  {t(item.name)}
                </Text>
                <IconButton
                  icon={item.show ? <ChevronUpIcon /> : <ChevronDownIcon />}
                  aria-label="Toggle"
                  variant="ghost"
                  colorScheme="blue"
                />
              </Flex>
              <Collapse in={item.show}>
                <Box className="space-y-2">
                  {item.keycodes.map((key, keyIndex) => (
                    <Box
                      key={keyIndex}
                      className={`p-2 rounded cursor-pointer ${
                        nowIndex === `${index}-${keyIndex}`
                          ? "bg-[rgba(55,65,81,.9)]"
                          : "hover:bg-[rgba(55,65,81,.7)]"
                      }`}
                      draggable={true}
                      onDragStart={(e) => {
                        e.dataTransfer.setData(
                          "keyCode",
                          JSON.stringify({
                            type: key.type,
                            keyName: t(key.name),
                            code1: key.code1,
                            code2: key.code2,
                            code3: key.code3,
                          })
                        );
                      }}
                      onClick={() => handleClick(index, keyIndex)}
                    >
                      {t(key.name)}
                    </Box>
                  ))}
                </Box>
              </Collapse>
            </Box>
          ))}
        </Box>
      </Box>

      <Modal isOpen={isOpen} onClose={onClose} isCentered>
        <ModalOverlay />
        <ModalContent minWidth="500px" height="260px">
          <ModalHeader
            fontSize="16px"
            display="flex"
            justifyContent="space-between"
            alignItems="center"
            height="48px"
            px="24px"
          >
            {t("openTitle")}
            <ModalCloseButton position="relative" top="unset" right="unset" />
          </ModalHeader>
          <ModalBody px="24px" pt="24px">
            <Text color="white" fontSize="14px" mb="16px" lineHeight="20px">
              {t("openTip")}
            </Text>
            <RadioGroup
              value={currentApp?.toString()}
              onChange={handleAppChange}
            >
              <Stack direction="row" spacing={4}>
                {appList.map((app, i) => (
                  <Radio
                    key={app.value.toString()}
                    value={app.value.toString()}
                  >
                    <Text className="color-white font-[13px] font-normal">
                      {app.label}
                    </Text>
                  </Radio>
                ))}
              </Stack>
            </RadioGroup>
          </ModalBody>

          <ModalFooter
            px="24px"
            pb="24px"
            display="flex"
            justifyContent="center"
            gap="12px"
          >
            <Button
              className="primary-btn"
              width="120px"
              height="40px"
              fontSize="16px"
              onClick={submitOpenApp}
            >
              {t("ok")}
            </Button>
            <Button
              variant="outline"
              onClick={onClose}
              width="120px"
              height="40px"
              fontSize="16px"
              border="1px solid #D7DEE3"
            >
              {t("cancel")}
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  );
};

export default SystemKey;
